import {lazy} from "react";
import React from "react";
import {deepClone} from "@/utils";
// 快速导入工具函数
const lazyLoad = (moduleName: String) => {
    const Module = lazy(() => import(`pages/${moduleName}`));
    return <Module/>;
};

const lazyLoadComp = (moduleName: String) => {
    const Module = lazy(() => import(`components/${moduleName}`));
    return <Module/>;
};

// 读取pages文件下下路由
const pagesFiles = require.context('@/pages', true, /\.tsx/);

// 定义基础路由
export const defaulyRoutes = [
    {
        path: '/login',
        component: lazyLoad("user/login"),
    },
];

// 拷贝路由对象
function deepCopyRoute<T>(raw: T): T {
    let copyData: any = Array.isArray(raw) ? [] : {};

    for (const key in raw) {
        const value: any = raw[key];
        // 如果是普通类型或者react元素则不深拷贝
        const condition = typeof value !== "object" || React.isValidElement(value);
        if (condition) {
            copyData[key] = value;
        } else if (typeof value === "object") {
            copyData[key] = deepCopyRoute(value);
        }
    }
    return copyData;
}

// 根据menus来筛选路由
export function filterRoute(menus: any) {

    // 1.默认加载所有路由
    let allRoutes: any = [];
    allRoutes = deepClone(defaulyRoutes);
    allRoutes.forEach((rout: any) => {
        menus.forEach((menu: any) => {
            if (rout.path == menu.path && rout.children) {
                rout.children.push(...mergeMenus(menu.children));
            }
        })
    })

    return allRoutes
}

function mergeMenus(arr: Array<any>) {
    return arr.map(item => {
        item.element = lazyLoad(item.component);
        return item
    })
}

export function getRouteMenu(menus: Array<any>) {
    //   menus 接口返回的路由
    // 1. 获取pages文件夹下的文件并处理格式
    const mergeFiles = pagesFiles.keys().slice(0, pagesFiles.keys().length / 2).map(item => item.replace(/^\.\//, "").replace(/\.\w+$/, ""))
    // 2. mergeFiles与入参的menus数组进行匹配过滤，去除不存在路由 得到有效路由数组
    const resultMenu: Array<any> = [];
    mergeFiles.map(file => {
        menus.map(menu => {
            if (menu.component == file) {
                menu.component = lazyLoad(menu.component);
                menu.title = menu?.meta.title || menu.name;
                menu.icon = menu?.meta.icon || null
                resultMenu.push(menu);
            }
        })
    })

    resultMenu.push(    {
        path: '*',
        component: lazyLoad("notFound/404"),
        meta: {
            title: '404',
        }
    });

    // 3. 给获取到的有效动态路由配置根路由，并将数据返回
    return {
        path: "/",
        component: lazyLoadComp("layouts/layout"),
        redirect: '/index',
        children: resultMenu
    }
}


